package com.nanhu.test.guesture;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;

public class MultiTouch extends Activity{
	private PointF start = new PointF();
	private Matrix matrix = new Matrix();
	private Matrix savedMatrix = new Matrix();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyView mv = new MyView(this);
		this.setContentView(mv);
	}
	
	class MyView extends View{
		static final int NONE = 0;
		static final int DRAG = 1;
		static final int ZOOM = 2;
		int mode = NONE;
		float oldDist = 1f;
		float mr = 50f;
		float mx = 100f, my = 100f;
		
		public MyView(Context context) {
			super(context);
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			Paint paint = new Paint();
			paint.setColor(Color.BLUE);
			canvas.drawCircle(mx, my, mr, paint);
		}
		
		private float spacing(MotionEvent event){
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return FloatMath.sqrt(x * x + y * y);
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			switch (event.getActionMasked()) {
				case MotionEvent.ACTION_DOWN: //单点触碰
//					mx = event.getX();
//					my = event.getY();
//					mr = 50;
					start.set(event.getX(), event.getY());
					mode = this.DRAG;
					break;
				case MotionEvent.ACTION_POINTER_DOWN:
					oldDist= this.spacing(event);
					mode = this.ZOOM;
					break;
				case MotionEvent.ACTION_MOVE:
					if(mode == DRAG){
						float dx = event.getX() - start.x;
						float dy = event.getY() - start.y;
						mx += dx;
						my += dy;
						start.set(event.getX(), event.getY());
					}else if(mode == ZOOM){
						float newDist = spacing(event);
						if(newDist > 10){
							mr = newDist/oldDist*100;
						}
					}
					break;
				case MotionEvent.ACTION_UP:
					mode = this.NONE;
					break;
				case MotionEvent.ACTION_POINTER_UP:
					mode = this.NONE;
					break;
				default:
					break;
			}
			invalidate();
			return true;
		}
	}
}
